package com.okbihuo.perm.core.auth.helper;

import com.okbihuo.perm.core.auth.domain.BaseAuthUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author Jr.November
 */
@Component
public class AuthHelper {

    /**
     * @return 若没有当前的登陆主体可能为空
     */
    public static Optional<BaseAuthUser> currentPrincipal() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        BaseAuthUser current = null;
        try {
            current = (BaseAuthUser) auth.getPrincipal();
            return Optional.of(current);
        }catch (Exception e) {
            return Optional.empty();
        }
    }

    /**
     * 专门用于审计操作的用户
     * @return "0" 系统自身
     */
    public static String currentAwareUserId() {
        Optional<BaseAuthUser> principalOptional = currentPrincipal();
        if (!principalOptional.isPresent()) {
            return "0";
        } else {
            return principalOptional.get().getAuditId();
        }
    }
}
